package cn.siat.auth.service;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import cn.siat.auth.form.CodeBody;
import cn.siat.auth.form.RegisterBody;
import cn.siat.auth.form.ResetBody;
import cn.siat.common.core.constant.*;
import cn.siat.common.core.domain.R;
import cn.siat.common.core.enums.RegisterTypeEnum;
import cn.siat.common.core.enums.UserStatus;
import cn.siat.common.core.exception.CaptchaException;
import cn.siat.common.core.exception.ServiceException;
import cn.siat.common.core.utils.StringUtils;
import cn.siat.common.core.utils.uuid.IdUtils;
import cn.siat.common.redis.service.RedisService;
import cn.siat.common.security.utils.SecurityUtils;
import cn.siat.system.api.RemoteUserService;
import cn.siat.system.api.domain.SysRole;
import cn.siat.system.api.domain.SysUser;
import cn.siat.system.api.model.LoginUser;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.map.HashedMap;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author siat
 */
@Component
@RequiredArgsConstructor
public class SysLoginService
{
    private final RemoteUserService remoteUserService;

    private final SysPasswordService passwordService;

    private final SysRecordLogService recordLogService;
    private final MailTool mailTool;
    private final RedissonClient redissonClient;
    @Autowired
    RedisService redisService;
    @Value("${pwd.public}")
    private String pwdPublic;
    @Value("${pwd.private}")
    private String pwdPrivate;
    private String decryptPwd(String password){
        RSA rsa = new RSA(pwdPrivate,null);
        try {
            password = StrUtil.str(rsa.decrypt(password, KeyType.PrivateKey), CharsetUtil.CHARSET_UTF_8);
        }catch(Exception e){
            throw new ServiceException("密码解密错误");
        }
        return password;
    }
    /**
     * 登录,可用手机号或者邮箱
     */
    public LoginUser login(String username, String password,long startTime)
    {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            recordLogService.recordLogininfor("-",username, Constants.LOGIN_FAIL, "用户/密码必须填写", System.currentTimeMillis()-startTime);
            throw new ServiceException("用户/密码必须填写");
        }
        password = decryptPwd(password);
        // 先解密
//        // 密码如果不在指定范围内 错误
//        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
//                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
//        {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户密码不在指定范围");
//            throw new ServiceException("用户密码不在指定范围");
//        }
//        // 用户名不在指定范围内 错误
//        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
//                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
//        {
//            recordLogService.recordLogininfor(username, Constants.LOGIN_FAIL, "用户名不在指定范围");
//            throw new ServiceException("用户名不在指定范围");
//        }
        // 查询用户信息
        R<LoginUser> userResult = remoteUserService.getUserInfo(username, SecurityConstants.INNER);

        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData()))
        {
            recordLogService.recordLogininfor("-",username, Constants.LOGIN_FAIL, "登录用户不存在",System.currentTimeMillis()-startTime);
            throw new ServiceException("用户不存在/密码错误");
        }

        if (R.FAIL == userResult.getCode())
        {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser userInfo = userResult.getData();
        SysUser user = userResult.getData().getSysUser();
        username = user.getUserName();
        String userId = user.getUserId();
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            recordLogService.recordLogininfor(userId,username, Constants.LOGIN_FAIL, "对不起，您的账号已被删除",System.currentTimeMillis()-startTime);
            throw new ServiceException("对不起，您的账号：" + username + " 已被删除");
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            recordLogService.recordLogininfor(userId,username, Constants.LOGIN_FAIL, "用户已停用，请联系管理员",System.currentTimeMillis()-startTime);
            throw new ServiceException("对不起，您的账号：" + username + " 已停用");
        }
        if ("1".equals(user.getIsAudit()))
        {
            recordLogService.recordLogininfor(userId,username, Constants.LOGIN_FAIL, "账号审核中",System.currentTimeMillis()-startTime);
            throw new ServiceException("您的账号：" + username + " 还在审核中，请耐心等待");
        }
        passwordService.validate(user, password,startTime);
        recordLogService.recordLogininfor(userId,username, Constants.LOGIN_SUCCESS, "登录成功",System.currentTimeMillis()-startTime);
        return userInfo;
    }
    public void logout(String userId,String loginName,long startTime)
    {
        recordLogService.recordLogininfor(userId,loginName, Constants.LOGOUT, "退出成功",System.currentTimeMillis()-startTime);
    }

    /**
     * 注册
     * @return
     */
    public R<Boolean> register(RegisterBody registerBody,long startTime)
    {
        String username = registerBody.getUsername();
        String password = decryptPwd(registerBody.getPassword());
        String email = registerBody.getEmail();
        String code = registerBody.getCode();
        String phone = registerBody.getPhone();
        String uuid = registerBody.getUuid();
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(username, password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH)
        {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(username);
        sysUser.setNickName(username);
        if(RegisterTypeEnum.PHONE.getType().equals(registerBody.getRegisterType())){
            if (StringUtils.isAnyBlank(phone, code))
            {
                throw new ServiceException("手机号码或验证码不能为空");
            }
            checkPhoneCaptcha(code,phone,"0");
            sysUser.setLogonMode("0");
            sysUser.setPhonenumber(phone);
        }else{
            if (StringUtils.isAnyBlank(email, code))
            {
                throw new ServiceException("邮箱或验证码不能为空");
            }
            checkEmailCaptcha(uuid,code,email);
            sysUser.setEmail(email);
            sysUser.setLogonMode("1");
        }
        sysUser.setRoleIds(new String[]{"1604777983837642752"});

        sysUser.setPassword(SecurityUtils.encryptPassword(password));
        R<Boolean> isSuccess = remoteUserService.registerUserInfo(sysUser, SecurityConstants.INNER);
        Boolean result = isSuccess.getData();
        if(result !=null && result){
            recordLogService.recordLogininfor("-",username, Constants.REGISTER, "注册成功",System.currentTimeMillis()-startTime);
            redisService.deleteObject(CacheConstants.PREFIX_SMS_MOBILE+phone+":0");
            redisService.deleteObject(CacheConstants.PREFIX_SMS_COUNT+phone+":0");
        }
        return isSuccess;
    }

    /**
     * 发送验证码
     * @param
     * @return
     */
    public String sendCode(CodeBody codeBody) {
        String email=codeBody.getEmail();
        int type=codeBody.getType();
        Integer code = (int)(Math.random() * 900000)+ 100000;
        if(StringUtils.isEmpty(email)){
            throw new ServiceException("邮箱不能为空");
        }
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
//        redisService.setCacheObject("email", email,new Long(60), TimeUnit.SECONDS);
        Map<String,String> map = new HashedMap<>();
        map.put("email",email);
        map.put("code",code.toString());
        redisService.setCacheObject(verifyKey, map, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);        //发送验证码邮件
        mailTool.send(email,code,type);
        return uuid;
    }

    /**
     * 校验邮箱验证码
     */
    public void checkEmailCaptcha(String uuid,String code,String email) throws CaptchaException
    {

        if (StringUtils.isEmpty(code))
        {
            throw new CaptchaException("验证码不能为空");
        }
        if (StringUtils.isEmpty(uuid))
        {
            throw new CaptchaException("验证码已失效");
        }
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        Map<String,String> map = null;
        try{
            map = redisService.getCacheObject(verifyKey);
        }catch (Exception e){
            System.err.println(e);
        }
        if(map == null){
            throw new CaptchaException("验证码超时");
        }else{

            if (!code.equalsIgnoreCase(map.get("code")))
            {
                throw new CaptchaException("验证码错误");
            }
            if (!email.equalsIgnoreCase(map.get("email")))
            {
                throw new CaptchaException("邮箱与验证码不符");
            }
        }
    }
    /**
     * 校验手机验证码
     */
    public void checkPhoneCaptcha( String smscode, String phone,String type) {

        if (StringUtils.isEmpty(smscode))
        {
            throw new CaptchaException("验证码不能为空");
        }
        RLock lock = redissonClient.getLock(CacheConstants.REDIS_LOCK+phone);
        lock.lock();
        try {
            Object smsCountObj = redisService.getCacheObject(CacheConstants.PREFIX_SMS_COUNT + phone + ":" + type);
            int smsCount = 0;
            if (smsCountObj != null) {
                smsCount = (int) smsCountObj;
            }
            // 超过4次直接锁了
            if (smsCount > 4) {
                throw new CaptchaException("验证码超过最大验证次数,已锁定手机号码");
            }
            Object code = redisService.getCacheObject(CacheConstants.PREFIX_SMS_MOBILE + phone + ":" + type);
            if (code == null) {
                throw new CaptchaException("手机验证码超时");
            }
            if (!smscode.equals(code)) {
                smsCount++;
                redisService.incr(CacheConstants.PREFIX_SMS_COUNT + phone + ":" + type, 1);
                throw new CaptchaException("手机验证码错误");
            }
        }finally {
            lock.unlock();
        }
    }
    public R<?> reset(ResetBody resetBody) {
        String password = resetBody.getPassword();
        String email = resetBody.getEmail();
        String phone = resetBody.getPhoneNumber();
        String code = resetBody.getCode();
        String uuid = resetBody.getUuid();
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(password))
        {
            throw new ServiceException("用户/密码必须填写");
        }
        /*if (StringUtils.isAnyBlank(email, String.valueOf(code)))
        {
            throw new ServiceException("邮箱或验证码不能为空");
        }*/

        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }

        // 重置用户信息
        SysUser sysUser = new SysUser();
        if(StringUtils.isNotEmpty(phone)){
            if (StringUtils.isAnyBlank(phone, code))
            {
                throw new ServiceException("手机号码或验证码不能为空");
            }
            checkPhoneCaptcha(code,phone,"1");
            sysUser.setPhonenumber(phone);
        }else{
            if (StringUtils.isAnyBlank(email, code))
            {
                throw new ServiceException("邮箱或验证码不能为空");
            }
            checkEmailCaptcha(uuid,code,email);
            sysUser.setEmail(email);
        }
        sysUser.setPassword(password);

        R<Boolean> isSuccess = remoteUserService.resetUserInfo(sysUser, SecurityConstants.INNER);
//        Boolean result = isSuccess.getData();
//        if(result !=null && result){
//            recordLogService.recordLogininfor(username, Constants.REGISTER, "重置成功");
//        }
        if(isSuccess.getData()){
            redisService.deleteObject(CacheConstants.PREFIX_SMS_MOBILE+phone+":1");
            redisService.deleteObject(CacheConstants.PREFIX_SMS_COUNT+phone+":1");
        }
        return isSuccess;
    }
}
